import React from 'react';
import util from 'util';
import {Button,Table ,Modal,message } from 'antd';
import { SearchDemo,RightButton,ColsEdit} from 'kpl';
import sys_dict from "sys_dict";
const confirm = Modal.confirm;

class TaskManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tblSource: [],
            totalCount: 0,
            isLoading: false,
            modalVisible: false,
            operateType: "ADD",
            operateData: {},
            modalTitle: "",
            projectList:[],
            defaultProKey:"",
            key:Math.random()
        };
        // 初始化查询参数
        this.searchParams={
            projectid:"",
            name:"",
            status:"",
            isrepeat:"",
            isauto:"",
            "page": 1,
            "rows": sys_dict.defaultPageSize.toString()
        };
        // 权限
        this.rights=[];
    }
    // 渲染之后
    componentDidMount() {
        this.rights=util.checkRights(["152","153"]);
        // 获取项目编号
        util.httpRequest({
            type: "POST", url: 'task050201.json', params: {},
            success: function (result) {
                if (result.ret_code == "0000") {
                    //  itemkey,itemvalue
                    let projectList=[];
                    for(let obj of result.rows){
                        projectList.push({itemkey:obj.id,itemval:obj.name});
                    }
                    let firstkey=projectList.length>0?projectList[0].itemkey:"";
                    console.log("list;",projectList);
                    this.searchParams.projectid=firstkey;
                    this.setState({
                        projectList:projectList,
                        defaultProKey: firstkey,
                        key:Math.random()
                    });
                    // 刷新情况
                    this.refresh(this.searchParams);
                }
            }.bind(this)
        });
        
        // 刷新列表
        this.refresh(this.searchParams);
    }

    refresh(paramdic) {
        // 打开等待框
        this.setState({isLoading: true});
        util.httpRequest({
            type: "POST", url: 'task050304.json', params: paramdic,
            success: function (result) {
                if (result.ret_code == "0000") {
                    this.setState({
                        tblSource: result.rows,
                        totalCount: result.total
                    });
                }
            }.bind(this)
            ,complete: function () {
                this.setState({
                    isLoading: false
                })
            }.bind(this)
        });
    }
    // 查询
    search(params) {
        // 分页初始化
        params.page = "1";
        params.rows = sys_dict.defaultPageSize.toString();
        params.status = params.job_status;
        this.searchParams=params;
        this.refresh(params);
    }
    // 打开编辑  qdqweqwe1231
    edit(record, index) {
        let obj = Object.assign({}, record);
        obj.job_status=obj.status.toString();
        obj.job_isrepeat=obj.isrepeat.toString();
        obj.job_isauto=obj.isauto.toString();

        this.setState({
            operateData: obj,
            modalVisible: true,
            operateType: 'EDIT'
        }, function () {
            var {setFieldsValue} = this.refs.form.getForm();
            setFieldsValue(obj);
        });
    }
    // 删除
    delete(record, index) {
        confirm({
            title: '您是否确认要删除该任务?',
            content: "",
            onOk: function () {
                util.httpRequest({
                    type: "POST", url: 'task050303.json', params: {id: record.id},
                    success: function (result) {
                        if (result.ret_code == "0000") {
                            this.search(this.searchParams);
                        }
                    }.bind(this)
                });
            }.bind(this)
        });
    }
    // pagesize改变
    onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
        let params = this.searchParams;
        params.rows = pageSize;
        params.page = current;
        this.refresh(params);
    }
    // page改变
    onChange(page) {
        console.log(page);
        let params = this.searchParams;
        params.page = page;
        this.refresh(params);
    }
    // 启用停用 213wqeqw3123
    operate(record, index) {
        let statusstr = record.status == "0"||record.status == "100"||record.status == "150"? "停用" : "启用";
        let title = '您是否确认要' + statusstr + '该任务';
        confirm({
            title: title,
            content: "",
            onOk: function () {
                console.log(index);
                util.httpRequest({
                    type: "POST",
                    url: 'task050305.json',
                    params: {id: record.id, status: record.status == "0"||record.status == "100"||record.status == "150"? "1" : "0"},
                    success: function (result) {
                        this.refresh(this.searchParams);
                    }.bind(this)
                });
            }.bind(this)
        });
    }
    // 执行任务 12qwe231231e
    execute(record, index) {
        confirm({
            title: "是否执行该任务",
            content: "",
            onOk: function () {
                console.log(index);
                util.httpRequest({
                    type: "POST",
                    url: 'task050306.json',
                    params: {id: record.id},
                    success: function (result) {
                        message.success('执行成功');
                        this.refresh(this.searchParams);
                    }.bind(this)
                });
            }.bind(this)
        });

    }
    // 初始化配置
    config() {
        const pagination = {
            total: this.state.totalCount,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: sys_dict.pageSizeOptions,
            defaultPageSize: sys_dict.defaultPageSize,
            onShowSizeChange: this.onShowSizeChange.bind(this),
            onChange: this.onChange.bind(this)
        };

        // 返回配置 12323
        return {
            tableConfig: {
                scroll:{ x: 1600 },
                pagination: pagination,
                loading: this.state.isLoading,
                dataSource: this.state.tblSource,
                columns: [
                {
                    title: '用户操作',
                    key: 'operation',
                    width:"150",
                    render: (text, record, index) => (
                        <span>
                            {this.rights[0]?<a onClick={this.edit.bind(this,record,index)}>修改</a>:null}
                            <span className="ant-divider"></span>
                            {this.rights[1]? <a onClick={this.delete.bind(this,record,index)}>删除</a>:null}
                            <span className="ant-divider"></span>
                            {record.isauto==1? <a onClick={this.operate.bind(this, record, index)}>{record.status == "0"||record.status == "100"||record.status == "150" ? "停用" : "启用"}</a>:null}
                            <span className="ant-divider"></span>
                            <a onClick={this.execute.bind(this,record,index)}>执行</a>
                        </span>
                    )
                },
                    {
                    title: '项目编号',
                    dataIndex: 'projectid',
                    key: 'projectid',
                    width:"110",
                }, {
                    title: '项目名称',
                    dataIndex: 'projectname',
                    key: 'projectname',
                    width:"110",
                },{
                    title: '名称',
                    dataIndex: 'name',
                    key: 'name'
                }, {
                    title: '描述',
                    dataIndex: 'remark',
                    key: 'remark'
                }, {
                    title: '调用服务名称',
                    dataIndex: 'link',
                    key: 'link'
                },{
                    title: '返回参数',
                    dataIndex: 'return_params',
                    key: 'return_params'
                }, {
                    title: '请求参数',
                    dataIndex: 'params',
                    key: 'params'
                },{
                    title: '执行规则',
                    dataIndex: 'cron',
                    key: 'cron'
                }, {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    width:"80",
                    render: function (value, data, rowIndex) {
                        var str = util.convert("job_status", value.toString());
                        return str;
                    }
                },{
                    title: '是否重复执行',
                    dataIndex: 'isrepeat',
                    key: 'isrepeat',
                    width:"110",
                    render: function (value, data, rowIndex) {
                        var str = util.convert("job_isrepeat", value.toString());
                        return str;
                    }
                }, {
                    title: '是否自动执行',
                    dataIndex: 'isauto',
                    key: 'isauto',
                    width:"110",
                    render: function (value, data, rowIndex) {
                        var str = util.convert("job_isauto", value.toString());
                        return str;
                    }
                }, {
                    title: '前置步骤',
                    dataIndex: 'forwardjobs',
                    key: 'forwardjobs'
                }, {
                    title: '服务编号',
                    dataIndex: 'servid',
                    key: 'servid'
                }]
            }
        };
    }
    // 取消弹出框
    handleCancel() {
        this.setState({
            modalVisible: false
        });
    }
    // 保存
    onSave() {
        var form = this.refs.form.getForm();
        form.validateFields((errors, values)=> {
            if (!!errors) {
                return;
            }
            // 关闭弹出框
            this.setState({
                modalVisible: false
            });
            // 编辑
            if (this.state.operateType == "EDIT") {
                values.id=this.state.operateData.id;
                values.status=values.job_status;
                values.isrepeat=values.job_isrepeat;
                values.isauto=values.job_isauto;
                this.update(values);
            }else {
                values.status=values.job_status;
                values.isrepeat=values.job_isrepeat;
                values.isauto=values.job_isauto;
                this.create(values);
            }
        });
    }
    // 更新
    update(values) {
        // 修改角色信息
        util.httpRequest({
            type: "POST", url: 'task050302.json', params: values,
            success: function (result) {
                if (result.ret_code == "0000") {
                    this.search(this.searchParams);
                }
            }.bind(this)
        });
    }
    // 新增12
    create(searchValues) {
        // 调用新增接口
        util.httpRequest({
            type: "POST", url: 'task050301.json', params: searchValues,
            success: function (result) {
                if (result.ret_code == "0000") {
                    this.search(this.searchParams);
                }
            }.bind(this)
        });
    }
    // 打开弹出框
    show() {
        console.log("shows");
        this.setState({
            modalVisible: true,
            operateType: "ADD",
            modalTitle:"新增",
            operateData: {}
        }, function () {
            var form = this.refs.form.getForm();
            form.resetFields();
        });
    }
    //
    disabledStartDate(startValue) {
        if (!startValue || !this.state.endValue) {
            return false;
        }
        return startValue.valueOf() > this.state.endValue.valueOf();
    }
    disabledEndDate(endValue) {
        if (!endValue || !this.state.startValue) {
            return false;
        }
        return endValue.valueOf() <= this.state.startValue.valueOf();
    }
    // 132ewrwr
    render() {
        let config = this.config();
        let projectList=this.state.projectList;
        const searchConfig = {
            searchTitle: "查询任务",
            searchInit: {
                projectid:this.state.defaultProKey
            },
            searchField: [
                [
                    {propsname: "项目编号", propsKey: "projectid", propsType: "select", key: "1111",
                        optionData:this.state.projectList
                    },
                    {propsname: "名称",propsKey: "name",propsType: "input",key: "1112"},
                    {propsname: "任务状态",propsKey: "job_status",propsType: "select",key: "1113"}
                ],
                [
                    {propsname: "是否可以重复执行",propsKey: "job_isrepeat",propsType: "select",key: "1114"},
                    {propsname: "是否自动执行",propsKey: "job_isauto",propsType: "select",key: "1115"}
                ]
            ]
        };

        // 新增任务 sda12
        const createConfig = {
            operateTitle: "新增任务",
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {rolename: "", roletype: "", descript: ""},
            operateColSm: 12,
            operateCol:{labelCol:6,wrapperCol:18},
            operateField: [
                [
                    {
                        propsname: "项目编号",
                        propsKey: "projectid",
                        propsType: "select",
                        key: "111",
                        optionData:this.state.projectList,
                        rules: [{required: true, whitespace: true, min: 0, message: '请选择'}]
                    },
                    {
                        propsname: "名称",
                        propsKey: "name",
                        propsType: "input",
                        key: "112",
                        rules: [{required: true, whitespace: true, min: 0, message: '请输入'}]
                    }
                ],
                [
                    {
                        propsname: "状态",
                        propsKey: "job_status",
                        propsType: "select",
                        key: "117",
                        rules: [{required: true, min: 0, message: '请选择'}]
                    },
                    {
                        propsname: "是否可以重复执行",
                        propsKey: "job_isrepeat",
                        propsType: "select",
                        key: "118",
                        rules: [{required: true, min: 0, message: '请选择'}]
                    }
                ],
                [
                    {
                        propsname: "是否自动执行",
                        propsKey: "job_isauto",
                        propsType: "select",
                        key: "119",
                        rules: [{required: true, min: 0, message: '请选择'}]
                    },
                    {
                        propsname: "前置步骤",
                        propsKey: "forwardjobs",
                        propsType: "input",
                        key: "120",
                        rules: [{ message: '请输入'}]
                    }
                ],
                [
                    {
                        propsname: "调用服务名称",
                        propsKey: "link",
                        propsType: "input",
                        key: "113",
                        rules: [{ required: true, whitespace: true, min: 0,message: '请选择'}]
                    },
                    {
                        propsname: "执行规则",
                        propsKey: "cron",
                        propsType: "input",
                        key: "114",
                        rules: [{message: '请选择'}]
                    }
                ],
                [
                    {
                        propsname: "请求参数",
                        propsKey: "params",
                        propsType: "input",
                        key: "115",
                        rules: [{ message: '请选择'}]
                    },
                    {
                        propsname: "返回参数",
                        propsKey: "return_params",
                        propsType: "input",
                        key: "116",
                        rules: [{required: true, whitespace: true, min: 0, message: '请选择'}]
                    }
                ],
                [
                    {
                        propsname: "描述",
                        propsKey: "remark",
                        propsType: "textarea",
                        key: "121",
                        optionData: [],
                        rules: [{ message: '请输入'}],
                        labelCol: 3,
                        wrapperCol: 21
                    }
                ]
            ]
        };

        return (
            <div>
                <SearchDemo key={this.state.key} search={this.search.bind(this)} searchConfig={searchConfig}></SearchDemo>
                <RightButton styleName="addBtn" propsKey="151" btnTxt="+  新增" oprate={this.show.bind(this)}> </RightButton>
                <Table {...config.tableConfig}></Table>
                <Modal visible={this.state.modalVisible} title={this.state.modalTitle} width="70%"
                       closable={false} footer={[
                        <Button key="back" type="ghost" size="large" onClick={this.handleCancel.bind(this)}>取消</Button>,
                        <Button key="submit" type="primary" size="large" onClick={this.onSave.bind(this)}>保存</Button>
                    ]}>
                    <ColsEdit ref="form" key="create" config={createConfig}></ColsEdit>
                </Modal>
            </div>
        );
    }
}

export default TaskManage;